package com.mz.mattress.api.util;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Http工具
 *
 * @author: guohaibin
 * @date: 2022/9/3
 */
public class HttpUtil {

    /**
     * 获取post请求的body
     *
     * @param request
     * @return String
     * @author guohaibin
     * @date 2022/9/3 15:48
     */
    public static String getPostBody(HttpServletRequest request) throws IOException {
        ServletInputStream is = request.getInputStream();
        int contentLength = Integer.parseInt(request.getHeader("content-length"));
        if (contentLength > 0) {
            int readLen = 0;
            int readLengthThisTime;
            byte[] message = new byte[contentLength];
            try {
                while (readLen != contentLength) {
                    readLengthThisTime = is.read(message, readLen, contentLength - readLen);
                    if (readLengthThisTime == -1) {// Should not happen.
                        break;
                    }
                    readLen += readLengthThisTime;
                }
                return new String(message);
            } catch (IOException e) {
            }
        }
        return "";
    }

}
